<template>
  <div>
    <!-- 头部 -->
    <header>
      <div class="top">
        <p>新增地址</p>
      </div>
    </header>
    <!-- 地址 -->

    <van-form ref="ffom">
      <van-cell-group>
        <van-field
          label="收货人"
          icon="question-o"
          placeholder="请输入用户名"
          v-model="form.username"
        />
        <van-field
          label="手机号码"
          placeholder="请输入手机号"
          :rules="telRules"
          :error-message="errMsg"
          name="mobile"
          @blur="teloin()"
          clearable
          v-model="form.userphone"
        />
        <van-cell
          title="所在地址"
          is-link
          @click="showPopup()"
          v-model="form.location"
        >
          <span class="showAddr">{{ form.location }}</span>
        </van-cell>
        <van-popup
          v-model="show"
          position="bottom"
          :style="{ height: '50%' }"
          @close="onClose()"
        >
          <van-area
            :area-list="areaList"
            :columns-placeholder="['请选择', '请选择', '请选择']"
            value="110000"
            @change="changeAddr"
            @cancel="cancelChoose"
            @confirm="onconfirm"
          />
        </van-popup>
        <van-field
          label="详细地址"
          placeholder="请选择地址"
          type="textarea"
          v-model="form.useraddress"
        />
      </van-cell-group>
      <van-cell-group>
        <van-cell title="标签">
          <van-radio-group
            v-model="form.label"
            direction="horizontal"
            class="radiop"
          >
            <van-radio name="家">家</van-radio>
            <van-radio name="公司">公司</van-radio>
            <van-radio name="学校">学校</van-radio>
          </van-radio-group>
        </van-cell>
        <van-cell title="设置默认地址">
          <van-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#ee0a24"
            inactive-color="#808080"
          />
        </van-cell>
        <van-cell>提醒：每次下单会默认推荐该地址</van-cell>
      </van-cell-group>
      <van-button type="primary" size="large" color="#ee0a24" @click="onedit()" v-if="this.$route.query.id" >保存编辑</van-button>
      <van-button type="primary" size="large" color="#ee0a24" @click="onInfo()" v-else>保存并使用</van-button
      >
      <van-button type="primary" size="large" color="#808080">重置</van-button>
    </van-form>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { areaList } from "@vant/area-data";
import { addressadd,addresslist,addressedit} from "../../request/api.js";
import { Toast } from "vant";
export default {
  props: [],
  components: {},
  data() {
    return {
      form: {
        username: "",
        userphone: "",
        useraddress: "",
        location: "",
        label: "",
        status: 1,
      },
      show: false,
      areaList: areaList,
      resAddr: "",
      userInfo: sessionStorage.getItem("user")
        ? JSON.parse(sessionStorage.getItem("user"))
        : {},
      errMsg: "",
      //存储需要保存的内容
      telRules: [
        {
          required: true,
          message: "手机号码不能为空",
          trigger: "onBlur",
        },
        {
          // 自定义校验规则
          validator: (value) => {
            return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
              value
            );
          },
          message: "请输入正确格式的手机号码",
          trigger: "onBlur",
        },
      ],
    };
  },
  computed: {
    ...mapGetters({}),
  },
  methods: {
    ...mapActions({}),
    showPopup() {
      this.show = true;
    },
    onClose() {
      this.show = false;
    },
    //改变地址
    changeAddr(picker) {
      //value=0改变省，1改变市，2改变区
      let val = picker.getValues();
      this.resAddr = val;
    },
    //选中
    onconfirm() {
      this.show = false;
      //选中地址成功后回显
      this.form.location =
        this.resAddr[0].name  +
        this.resAddr[1].name +
        this.resAddr[2].name;
      console.log(this.resAddr, "即将传给后端的省市区信息");
    },
    //取消
    cancelChoose() {
      this.show = false;
    },
    //判断手机号
    //vant局部验证，注意验证的内容要用van-form包裹住
    teloin() {
      this.$refs.ffom
        .validate("mobile")
        .then(() => {
          this.errMsg = "";
        })
        .catch(() => {
          this.errMsg = "请输入正确手机号";
        });
    },
    //清空
    empty(){
      this.form={
         username: "",
        userphone: "",
        useraddress: "",
        location: "",
        label: "",
        status: 1,
      }
    },
    //初次添加地址
    onInfo() {
      //form是绑定的所有数据内容合集
      this.form.uid = this.userInfo.uid;
      console.log(this.form);
      //调用添加接口
      addressadd(this.form).then((res) => {
        if (res.data.code == 200) {
          Toast.success(res.data.msg);
          //清空
          this.empty();
          //跳转页面
          this.$router.push("/tureoder")
        } else {
          Toast.fail(res.data.msg);
        }
      });
    },
    //修改地址
    onedit(){
      addressedit(this.form).then(res=>{
        console.log(res.data.list)
        Toast.success(res.data.msg);
        this.$router.push("/tureoder")
        
      })
    }
  },
  mounted() {
    if(this.$route.query.id){
      console.log(this.$route.query.id)
      addresslist({uid:this.userInfo.uid}).then(res=>{
          res.data.list.forEach(item=>{
              if(item.id == this.$route.query.id ){
                  this.form = item
              }
          })
      })
    }
   
  },
};
</script>
<style scoped>
header {
  background: #ff6040;
  height: 1.45rem;
}
header .top {
  height: 0.8rem;
  display: flex;
  color: #ffdfd8;
  align-items: center;
  padding: 0.3rem 0.12rem 0.12rem 0.33rem;
  box-sizing: border-box;
}
header .top p {
  font-size: 0.5rem;
  margin: 0.5rem 1.45rem 0 2.2rem;
}
.radiop {
  font-size: 0.4rem;
}
.van-cell__title {
  flex: none;
  width: 2.2rem;
}
</style>